package com.laotang.第_9_章_二叉树.力扣_117_填充每个节点的下一个右侧节点指针II;

import java.util.LinkedList;
import java.util.Queue;

public class _117_populating_next_right_pointers_in_each_node_ii {
    // 时间复杂度：O(n)
    // 空间复杂度：O(n)
    public Node connect1(Node root) {
        if (root == null) return null;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node prev = null;
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);

                if (prev != null) prev.next = node;
                prev = node;
            }
        }
        return root;
    }

    // 时间复杂度：O(n)
    // 空间复杂度：O(1)
    public Node connect(Node root) {
        if (root == null) return null;

        Node curr = root;
        Node dummy = new Node();
        while (curr != null) {
            Node prev = dummy;
            //  开始处理一层所有的节点
            while (curr != null) {
                if (curr.left != null) {
                    prev.next = curr.left;
                    prev = prev.next;
                }
                if (curr.right != null) {
                    prev.next = curr.right;
                    prev = prev.next;
                }
                curr = curr.next;
            }
            // 处理下一层，来到下一层的第一个节点
            curr = dummy.next;
            dummy.next = null;
        }

        return root;
    }
}
